const Router = require('koa-router');
const router = new Router();
const tool = require('../../tools/tool')
const {db, QueryTypes} = require("../../models/db");

router.post('/menu/save', async ctx => {
    try {
        let mod = 'menuV5';
        let formData = ctx.request.body.formData
        try {
            let id = formData.id
            delete formData.id
            if(id) {
                await db.models[mod].update(formData, {
                    where: {
                        id: id
                    }
                })
            }
            else {
                let pid = formData.pid ? formData.pid : null;
                let mode = null
                if(pid) {
                    mode = await db.models[mod].findOne({
                        where: {
                            pid
                        },
                        order: [['code', 'desc']]
                    })
                }
                else {
                    mode = await db.models[mod].findOne({
                        where: {
                            tenantId: ctx.user.tenantId,
                            pid: 0
                        },
                        order: [['code', 'desc']]
                    })
                }
                if (!pid) {
                    if(mode) {
                        formData.code = (parseInt(mode.code) + 1).toString()
                    }
                    else {
                        formData.code = '100';
                    }
                }
                else {
                    if(mode) {
                        formData.code = (parseInt(mode.code) + 1).toString()
                    }
                    else {
                        let pidMode = await db.models[mod].findOne({
                            where: {id: pid}
                        })
                        formData.code = pidMode.code + '100'
                    }
                }
                formData = await db.models[mod].create(formData)
            }
            return ctx.suc('保存成功', formData)
        } catch (e) {
            return  ctx.err(e)
        }
    }
    catch (error) {
       return  ctx.err(error)
    }
})

module.exports = router;
